<?php

namespace app\admin\service;

use app\models\ConsultorModel;
use app\models\CourseLogModel;
use app\models\DictionaryModel;
use app\models\FollowUpLogModel;
use app\models\MenuModel;
use app\models\PayFlowModel;
use think\Db;

/**
 * Class CommonService.
 */
class CommonService
{
    public static function mergeCate($arr, $pidName, $parent_id = 0, $level = 0)
    {
        $res = [];
        foreach ($arr as $v) {
            if ($v[$pidName] === $parent_id) {
                $v['disabled'] = false;
                foreach ($arr as $v1) {
                    if ($v1[$pidName] === $v['id']) {
                        $v['disabled'] = true;

                        break;
                    }
                }

                $v['level'] = $level;
                $res[] = $v;
                $res = array_merge($res, self::mergeCate($arr, $pidName, $v['id'], $level + 1));
            }
        }

        return $res;
    }

    /**
     * @param $ad_p_name
     *
     * @return mixed
     */
    public static function getContentType($ad_p_name)
    {
        $where = [
            'ad_name' => $ad_p_name,
        ];

        return PositionModel::where($where)->value('ad_type');
    }

    /**
     * 获取广告类型.
     *
     * @param $ad_s_id
     *
     * @return mixed
     */
    public static function getSubjectName($ad_s_id)
    {
        $where = [
            'id' => $ad_s_id,
        ];

        return SubjectModel::where($where)->value('ad_m');
    }

    /**
     * 获取当前的pid.
     *
     * @param $title
     * @param $controller
     * @param $action
     *
     * @return mixed
     */
    public static function getCurrentPid($title, $controller, $action)
    {
        $code = $controller.'/'.$action;
        $memuModel = new MenuModel();
        $condition = [
            'title' => $title,
            'menu_name' => $code,
        ];

        return $memuModel->where($condition)->value('pid');
    }

    /**
     * 获取pid.
     *
     * @param $title
     * @param $menu_name
     *
     * @return mixed
     */
    public static function getTwoPid($title, $menu_name)
    {
        $memuModel = new MenuModel();
        $condition = [
            'title' => $title,
            'menu_name' => $menu_name,
        ];

        return $memuModel->where($condition)->value('pid');
    }

    /**
     * 获取上级标题名称.
     *
     * @param $pid
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getSuperiorTitle($pid)
    {
        $memuModel = new MenuModel();

        return $memuModel->where('id', $pid)->find();
    }

    /**
     * 获取当前标题名称.
     *
     * @param $controller
     * @param $action
     *
     * @return mixed
     */
    public static function getCurrentTitle($controller, $action)
    {
        $code = $controller.'/'.$action;
        $memuModel = new MenuModel();

        return $memuModel->where('menu_name', $code)->value('title');
    }

    /**
     * 获取广告类型.
     *
     * @param mixed $type
     */
    public static function getAdType($type)
    {
        $value = '';
        switch ($type) {
            case 1:
                $value = '图片';

                break;
            case 2:
                $value = '文字';

                break;
            case 3:
                $value = '图文';

                break;
            case 4:
                $value = '动画';

                break;
            case 5:
                $value = '视频';

                break;
            case 6:
                $value = '短信';

                break;
            case 7:
                $value = '链接';

                break;
            case 8:
                $value = '二维码';

                break;
        }

        return $value;
    }

    /**
     * 写入订单操作人记录.
     *
     * @param $uid
     * @param $name
     * @param $ordernumber 订单号
     * @param $ctype 操作类型
     * @param $wtype 工作类型
     * @param $content 操作描述
     */
    public static function writeOrderOperatorRecord($uid, $name, $ordernumber, $ctype, $wtype, $content)
    {
        $data = [
            'order_number' => $ordernumber,
            'user_id' => $uid,
            'user_name' => $name,
            'ctype' => $ctype,
            'wtype' => $wtype,
            'content' => $content,
            'operation_time' => date('Y-m-d H:i:s', time()),
        ];
        OrderLogModel::create($data);
    }

    /**
     * 写入退货、退单记录.
     *
     * @param $code 支付单号
     * @param $ordernumber 订单号
     * @param $order_list_id 订单商品列表ID
     * @param $proid 商品id
     * @param $num 商品数量
     * @param $price 金额
     * @param $type 订单操作类型 0-取消 1-异常
     */
    public static function writeFlagRecord($code, $ordernumber, $order_list_id, $proid, $num, $price, $type)
    {
        $refund_number = 'TK'.time();
        $data = [
            'code' => $code, //支付单号
            'order_number' => $ordernumber, //订单号
            'refund_number' => $refund_number, //退款单号
            'order_list_id' => $order_list_id, //订单商品列表ID
            'pro_id' => $proid, //商品ID
            'num' => $num, //商品数量
            'price' => $price, //金额
            'type' => $type, //订单操作类型 0-取消 1-异常
            'status' => 0, //1：已退款，0：未退款 默认0
        ];
        OrderFlagModel::create($data);
    }

    /**
     * 写入车厢退款金额记录.
     *
     * @param $order_code
     * @param $paytime
     * @param $paydate
     * @param $amount
     * @param $protype
     * @param $mch_id
     * @param $mch_name
     * @param $base_id
     * @param $base_name
     * @param $remark
     * @param $trxid
     */
    public static function writeInRefundFeeRecord($order_code, $paytime, $paydate, $amount, $protype, $mch_id, $mch_name, $base_id, $base_name, $remark, $trxid)
    {
        $data = [
            'order_code' => $order_code, //支付单号
            'paytime' => $paytime, //时间戳
            'paydate' => $paydate, //时间
            'amount' => -$amount, //金额
            'type' => 2, //流水类型：1收入，2退款
            'protype' => $protype, //0：外卖，1：车厢，-1：长尾（优选）
            'mch_id' => $mch_id, //商户号
            'mch_name' => $mch_name, //商户名称
            'base_id' => $base_id, //基地ID
            'base_name' => $base_name, //基地名称
            'trxid' => $trxid, //平台支付单号
            'remark' => $remark,
        ];
        PayFlowAModel::create($data);
    }

    /**
     * 写入外卖、长尾、优选退款金额记录.
     *
     * @param $order_code
     * @param $paytime
     * @param $paydate
     * @param $amount
     * @param $protype
     * @param $mch_id
     * @param $mch_name
     * @param $com_id
     * @param $com_name
     * @param $remark
     * @param $trxid
     */
    public static function writeOutRefundFeeRecord($order_code, $paytime, $paydate, $amount, $protype, $mch_id, $mch_name, $com_id, $com_name, $remark, $trxid)
    {
        $data = [
            'order_code' => $order_code, //支付单号
            'paytime' => $paytime, //时间戳
            'paydate' => $paydate, //时间
            'amount' => -$amount, //金额
            'type' => 2, //流水类型：1收入，2退款
            'protype' => $protype, //0：外卖，1：车厢，-1：长尾（优选）
            'mch_id' => $mch_id, //商户号
            'mch_name' => $mch_name, //商户名称
            'com_id' => $com_id, //公司ID
            'com_name' => $com_name, //公司名称
            'trxid' => $trxid, //平台支付单号
            'remark' => $remark,
        ];
        PayFlowBModel::create($data);
    }

    /**
     * @param $ds_com
     *
     * @return string
     */
    public static function getCompanyText($ds_com)
    {
        $value = '';
        switch ($ds_com) {
            case 'shentong':
                $value = '申通快递';

                break;
            case 'yuantong':
                $value = '圆通速递';

                break;
            case 'zhongtong':
                $value = '中通快递';

                break;
            case 'huitongkuaidi':
                $value = '百世汇通';

                break;
            case 'yunda':
                $value = '韵达快递';

                break;
            case 'shunfeng':
                $value = '顺丰快递';

                break;
            case 'youzhengguonei':
                $value = '邮政快递';

                break;
        }

        return $value;
    }

    /**
     * 订单类型.
     *
     * @param $protype
     *
     * @return string
     */
    public static function getProtypeText($protype)
    {
        $value = '';
        switch ($protype) {
            case -1:
                $value = '长尾订单';

                break;
            case 0:
                $value = '外卖订单';

                break;
            case 1:
                $value = '车厢订单';

                break;
        }

        return $value;
    }

    /**
     * 支付状态
     *
     * @param $pay_status
     *
     * @return string
     *                支付状态 0:未支付;1:已支付;2:部分退款;3:已退款;
     */
    public static function getPayStatusText($pay_status)
    {
        $value = '';
        switch ($pay_status) {
            case 0:
                $value = '未支付';

                break;
            case 1:
                $value = '已支付';

                break;
            case 2:
                $value = '部分退款';

                break;
            case 3:
                $value = '已退款';

                break;
        }

        return $value;
    }

    /**
     * 订单状态
     *
     * @param $status
     *
     * @return string
     *                订单状态 0:已下单;1:已支付;2:已接单;3:已完成;4:已取消;5:已关闭;-1:已作废;
     */
    public static function getStatusText($status)
    {
        $value = '';
        switch ($status) {
            case -1:
                $value = '已作废';

                break;
            case 0:
                $value = '已下单';

                break;
            case 1:
                $value = '已支付';

                break;
            case 2:
                $value = '已接单';

                break;
            case 3:
                $value = '已完成';

                break;
            case 4:
                $value = '已取消';

                break;
            case 5:
                $value = '已关闭';

                break;
        }

        return $value;
    }

    /**
     * 支付方式.
     *
     * @param $paytype
     *
     * @return string
     *                支付方式:0未知,1微信支付,2支付宝,3通联支付,4京东支付,5建行支付,6现金支付
     */
    public static function getPaytypeText($paytype)
    {
        $value = '';
        switch ($paytype) {
            case 0:
                $value = '未知';

                break;
            case 1:
                $value = '微信支付';

                break;
            case 2:
                $value = '支付宝';

                break;
            case 3:
                $value = '通联支付';

                break;
            case 4:
                $value = '京东支付';

                break;
            case 5:
                $value = '建行支付';

                break;
            case 6:
                $value = '现金支付';

                break;
        }

        return $value;
    }

    /**
     * 订单来源.
     *
     * @param $ordertype
     *
     * @return string
     *                订单来源  0:商城订单1:手机当面付2:手工下单3:扫码下单4:金额下单5:OTA订单6:12306下单
     */
    public static function getOrdertypeText($ordertype)
    {
        $value = '';
        switch ($ordertype) {
            case 0:
                $value = '商城订单1';

                break;
            case 1:
                $value = '手机当面付';

                break;
            case 2:
                $value = '手工下单';

                break;
            case 3:
                $value = '扫码下单';

                break;
            case 4:
                $value = '金额下单';

                break;
            case 5:
                $value = 'OTA订单';

                break;
            case 6:
                $value = '12306下单';

                break;
        }

        return $value;
    }

    /**
     *  获取字典名称.
     * @param $id
     * @return array
     * @throws \think\exception\DbException
     */
    public static function getDictionaryName($id)
    {
        if (!is_numeric($id)) {
            return [];
        }

        return DictionaryModel::get($id)['name'];
    }

    /**
     * 生成单号.
     * @return string
     */
    public static function generateNumber()
    {
        $number = '';
        $year = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
        $number .= $year[intval(date('Y')) - 2019] . date('mdHis').substr(microtime(), 2, 3) . sprintf('%02d', rand(0, 99));
        return $number;
    }


    /**
     * 生成学号
     * @return string
     */
    public static function generateStudentNumber()
    {
        $number = '';
        $year = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
        $number .= 'X'.$year[intval(date('Y')) - 2019] . date('mdHis').substr(microtime(), 2, 3) . sprintf('%02d', rand(0, 99));
        return $number;
    }

	/**
	 * User: wufeng
	 * Date: 2019/4/16
	 *
	 * @param $contract_number
	 * @param $type
	 * @param $amount
	 * @param $remark
	 * @param $campus_id
	 * @param $receipt_number
	 */
    public static function writeFlowRecord($contract_number, $type, $amount, $remark, $campus_id, $receipt_number, $pay_channel)
    {
        $data = [
            'contract_number' => $contract_number, //订单编号
            'operator' => get_current_name(),
            'paytime' => time(), //时间戳
            'paydate' => date('Y-m-d H:i:s', time()), //时间
            'type' => $type, //流水类型：1收入，2退款
            'remark' => $remark,
            'receipt_number' => $receipt_number,
            'campus_id' => $campus_id,
            'pay_channel' => $pay_channel //付款通道
        ];
        if (1 === $type) {
            $data['amount'] = $amount; //金额
        } elseif (2 === $type) {
            $data['amount'] = -$amount; //金额
        }

        PayFlowModel::create($data);
    }

    /**
     * @param $contract_number
     * @param $course
     * @param $campus
     */
    public static function writeCourseRecord($contract_number, $course, $campus, $record_status)
    {
        $data = [
            'contract_number' => $contract_number, //订单编号
            'course' => $course, //课程
            'campus' => $campus, //校区
            'record_status' => $record_status, //记录来源
        ];
        CourseLogModel::create($data);
    }

    /**
     * @param $student_id
     * @param $contract_number
     * @param $contract_type
     */
    public static function writeSignContract($student_id, $contract_number, $contract_type)
    {
        $data = [
            'student_id' => $student_id, //学员ID
            'contract_number' => $contract_number, //签约订单编号
            'contract_type' => $contract_type, //类型
        ];
        ConsultorModel::create($data);
    }

    /**
     * @param $status
     *
     * @return string
     */
    public static function getContractText($status)
    {
        $value = '';
        switch ($status) {
            case '1':
                $value = '已付款';

                break;
            case '2':
                $value = '未付款';

                break;
        }

        return $value;
    }

	/**
	 * 学员客户跟进沟通记录写入
	 * modify by Small Y
	 *
	 * @param $sid
	 * @param $campus_id
	 * @param $type
	 * @param $content
	 * @param $mode
	 * @param $follow_up
	 */
    public static function writeFollowUpLog($sid,$campus_id,$type,$content,$mode,$follow_up)
    {
        $data = [
            'student_id' => $sid, //学员客户ID
            'campus_id' => $campus_id, //校区id
            'user_id' => get_current_id(),
            'timestamp' => time(),//时间戳
            'date' => date('Y-m-d', time()), //日期
            'time' => date('Y-m-d H:i:s', time()), //时间
            'type' => $type, //类型：1系统跟进，2沟通
            'content' => $content,
            'mode' => $mode,
			'follow_up' => $follow_up //跟进状态：33未分配 34未处理 35已跟进 36已预约 103已上门 104已交定金 105已丢单
        ];
        FollowUpLogModel::create($data);
    }

	/**
	 * User: wufeng
	 * Date: 2020/03/14
	 *
	 * @param $notice_object
	 * @param $notice_name
	 * @param $notice_content
	 * @param $flag  1:家长端  2:机构端
	 * @param $notice_type  1:普通通知  2:系统通知
	 */
	public static function writeNotice($notice_object,$notice_name,$notice_content,$flag,$notice_type)
	{
		//审批通知
		$notice = [];
		$notice['notice_time'] = date('Y-m-d H:i:s'); //通知时间
		$notice['user_id'] = get_current_id(); //操作审批人的id
		$notice['notice_object'] = $notice_object; //通知对象
		$notice['notice_name'] = $notice_name; //通知名称
		$notice['content'] = $notice_content; //具体内容
		$notice['notice_type'] = 1; //通知方向：1机构端、家长端；2机构端；3家长端
		$notice['status'] = 1; //存稿还是发布：1发布 2存稿

		Db::name('edu_my_notice')->insert($notice);  //插入通知表
		$notice_id = Db::name('edu_my_notice')->getLastInsID();
		$_data = [];
		$notices = explode(',', $notice['notice_object']);
		foreach ($notices as &$notice) {
			$arr = [];
			$arr['notice_id'] = $notice_id;
			$arr['notice_object_id'] = $notice;
			$arr['n_type'] = $flag;
			$arr['notice_type'] = $notice_type;
			$_data[] = $arr;
		}
		Db::name('edu_my_notice_object')->insertAll($_data);
	}
}
